import { AxiosError } from "axios";
import { ElNotification } from "@chulei-ui/element-plus";
import { ApiError, HttpError } from "@chulei-ui/utils";
import router from "../../routers";

export const DEFAULT_TOOLTIP = (error: HttpError | ApiError | AxiosError, duration: number) => {
  if (error instanceof ApiError && error.details) {
    const fieldErrors = JSON.parse(error.details) as unknown as Record<string, string>;
    ElNotification({
      dangerouslyUseHTMLString: true,
      title: "温馨提示",
      message: `<ul>${Object.keys(fieldErrors)
        .map((field) => `<li><span style="color: var(--el-color-danger)">${fieldErrors[field]}</span></li>`)
        .join("")}</ul>`,
      type: "error",
      duration: 0,
    });
  } else {
    ElNotification({
      title: "温馨提示",
      message: error.message,
      type: "error",
      duration,
    });
  }
};

export type Tooltip = (error: HttpError | ApiError | AxiosError, duration: number) => void;

export async function tooltip<T>(
  callback: () => Promise<T>,
  duration = 10 * 1000,
  tooltip: Tooltip = DEFAULT_TOOLTIP
): Promise<T> {
  try {
    return await callback();
  } catch (e) {
    //@ts-ignore
    if (e.name) {
      tooltip(e as HttpError, duration);
    } else if (e instanceof HttpError || e instanceof ApiError || e instanceof AxiosError) {
      tooltip(e, duration);
      if (e.code === 3001) {
        await router.push("/login");
      }
    }
    throw e;
  }
}
